package cn.stimd.spring.beans.factory.support;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Comparator;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class AutowireUtils {

    /**
     * 对构造器进行排序，public的优先级高于非public，参数越多的优先级越高
     */
    public static void sortConstructors(Constructor<?>[] constructors) {
        Arrays.sort(constructors, new Comparator<Constructor<?>>() {
            @Override
            public int compare(Constructor<?> c1, Constructor<?> c2) {
                boolean p1 = Modifier.isPublic(c1.getModifiers());
                boolean p2 = Modifier.isPublic(c2.getModifiers());
                if (p1 != p2) {
                    return (p1 ? -1 : 1);
                }
                int c1pl = c1.getParameterTypes().length;
                int c2pl = c2.getParameterTypes().length;
                return (c1pl < c2pl ? 1 : (c1pl > c2pl ? -1 : 0));
            }
        });
    }
}
